// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.superlists.servlet;

import com.google.superlists.model.State;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet for the home page, which handles state parameters and redirects to
 * an appropriate page.
 *
 * @author sven@google.com (Sven Mawson)
 */
public class HomeServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    // Authorize the user immediately. We always authorize before we allow any
    // other action to occur.
    AuthorizationAction action = new AuthorizationAction(this, req, resp);
    action.execute();

    // If there was state, deserialize it and redirect appropriately.
    String stateParam = req.getParameter("state");
    if (stateParam != null) {
      State state = new State(stateParam);
      if (state.ids != null && state.ids.size() > 0) {
        String id = state.ids.iterator().next();
        resp.sendRedirect("/edit?id=" + id);
        return;
      }
    }

    // Check for an "id" parameter, if we find it we redirect to the edit page.
    String id = req.getParameter("id");
    if (id != null) {
      resp.sendRedirect("/edit?id=" + id);
      return;
    }

    // No state, redirect to create a new list.
    resp.sendRedirect("/edit?id=");
  }
}
